package com.hua.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hua.pojo.UserInfo;
import com.hua.result.R;
import com.hua.service.BlogService;
import com.hua.service.CommentService;
import com.hua.service.QuestionService;
import com.hua.service.UserInfoService;
import com.hua.utils.HuaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

/**
 * @author ONE-X
 * @date 2020/11/09
 */
@Controller
@RequestMapping("/userinfo")
public class UserInfoController {
	static Logger logger = Logger.getLogger("UserInfoController");

	@Autowired
	UserInfoService userInfoService;
	@Autowired
	BlogService blogService;
	@Autowired
	QuestionService questionService;
	@Autowired
	CommentService commentService;

	@ResponseBody
	@GetMapping("/information")
	public String userInfo(){
		String uid = HuaUtil.returnAuthentication();
		UserInfo userInfo = userInfoService.getById(uid);
		// 昵称
		String nickname = userInfo.getNickname();
		// 爱好
		String s = userInfo.getHobby();
		String[] hobby = s!=null?s.split(","):null;
		// 博客的数量
		Integer blogCount = blogService.findBlogByAuthorCount(uid);
		// 问题数量
		Integer questionCount = questionService.findQuestionByAuthorCount(uid);
		// 回复的数量
		Integer commentCount = commentService.findQuestionByAuthorCount(uid);
		R r = R.ok();
		Map<String, Object> map = new HashMap<>();
		map.put("nickname",nickname);
		map.put("hobby",hobby);
		map.put("blogCount",blogCount);
		map.put("questionCount",questionCount);
		map.put("commentCount",commentCount);
		r.setData(map);
		return JSON.toJSONString(r);
	}

	/**
	 *  获取用户基本信息
	 */
	@ResponseBody
	@PostMapping("/info")
	public String getInfo(){
		UserInfo userinfo = userInfoService.getById(HuaUtil.returnAuthentication());
		R r = R.ok();
		Map<String, Object> map = new HashMap<>();
		map.put("userinfo",userinfo);
		r.setData(map);
		return JSON.toJSONString(r);
	}
	/**
	 * 跟新用户信息
	 */
	@ResponseBody
	@PostMapping("/infosave")
	public String userInfoSave(@RequestBody UserInfo userInfo){
		R r = R.ok();
		try{
			String uid = HuaUtil.returnAuthentication();
			userInfo.setUid(uid);
			userInfoService.updateById(userInfo);
		}catch (Exception e){
			logger.warning("更新用户信息时出现了错误");
			e.printStackTrace();
			r = R.error();
		}

		return JSON.toJSONString(r);
	}
}
